from flask import Flask  # 1.
from flask import render_template  # 3.
from flask import url_for
from flask import jsonify
from flask import request,json
# 下面这个包用来检测文件文件名称是否重名，做名称的安全检测
from werkzeug.utils import secure_filename


"""
from flask import Flask,render_template
from flask import url_for,jsonify
from flask import request
"""
# 1.
app = Flask(__name__)

# 1.
@app.route('/')
def hello_world():
    return 'Hello World!'

# 2.
@app.route('/user/<name>')
def username(name):
    # 通过数据库查询
    # 通过数据库修改
    # 其他业务操作
    # 修改相关信息,并且返回到前台
    if(name == "张三"):
        name = "真是张三"
    else:
        name = "不是张三，而是" + name
    return '<h1>hello,%s</h1>' % name
# 3.
@app.route('/user')
def user():
    users = [['张三','男','重庆'],
             ['李四','女','河南']]
    return render_template("user.html",list=users)

# 2021/10/14周四下午第一节
@app.route('/url/')
def redirect_to_url():
    return url_for('post_show',post_id = 666)

"""
localhost:5000/post/666
"""
@app.route('/post/<int:post_id>')
def post_show(post_id):
    return 'post ID : %d' % post_id

@app.route('/getJson')
def getJson():
    data = {
        "name":"张三",
        "sex":"男",
        "age":"20",
        "address":"xxxxx"
    }
    return  jsonify(data)


# Get传参，Post传参，Put传参
"""
localhost:5000/login?username=zhangsan&address=重庆财经学院
Key         Value
username    zhangsan
address     重庆财经学院
"""
@app.route('/login',methods=['GET','POST','PUT'])
def login():
    data = "无数据"
    if request.method == 'GET':
        print("当前请求方法是GET")
        username = request.args.get("username")
        address = request.values.get("address")
        data = {
            "username":username,
            "address":address
        }
    elif request.method == 'POST':
        print("当前请求方法是POST")
        username = request.args.get("username")
        address = request.values.get("address")
        data = {
            "username": username,
            "address": address
        }
    elif request.method == 'PUT':
        print("当前请求方法是PUT")
        username = request.args.get("username")
        address = request.values.get("address")
        data = {
            "username": username,
            "address": address
        }
    print(data)
    return jsonify(data)
'''
返回Json，或者说从前端接受Json数据过来，又返回，中间写业务程序
'''
# 传递json
@app.route('/passJson',methods=['POST'])
def passJson():
    data = json.loads(request.get_data(as_text=True))
    # 写业务程序
    return jsonify(data)

"""
上传文件（重点），步骤1：创建路由，创一个到静态文件的路由，在静态文件中有文件上传功能。
浏览器访问：http://localhost:5000/upload/index
"""
@app.route('/upload/index')
# 只用来做跳转，跳转到upload2.html
def toUploadPage():
    return render_template('upload2.html')
'''
步骤2:静态文件中有文件上传功能，点击该功能上传文件
'''
@app.route('/upload',methods=['POST'])
def upload():
    if request.method == 'POST':
        file = request.files['file']  # ['file']对应name="file"
        print(request.files)

        # 保存的时候不能和本地的文件重名，用一个包
        file.save(secure_filename(file.filename))
        #  可以做其他业务，比如人脸识别等等
        return "文件上传成功!"
    else:
        return render_template('upload2.html')

'''
访问数据库（mysql）
'''



# 1.
if __name__ == '__main__':
    app.debug = True
    app.run()


